#pragma once
#include <memory>
#include <fmt/core.h>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/CommonRequest.h>
#include <alibabacloud/core/CommonClient.h>
#include <alibabacloud/core/CommonResponse.h>
#include "../logger.hpp"

namespace shared{

namespace infra {

class DMSClient 
{
public:
    DMSClient(const std::string& accessKeyId, const std::string& accessKeySecret) 
    {
        AlibabaCloud::InitializeSdk();
        AlibabaCloud::ClientConfiguration configuration("cn-chengdu");
        configuration.setConnectTimeout(1500);
        configuration.setReadTimeout(4000);
        AlibabaCloud::Credentials credential(accessKeyId, accessKeySecret);
        client_ = std::make_unique<AlibabaCloud::CommonClient>(credential, configuration);
    }
    ~DMSClient() { AlibabaCloud::ShutdownSdk(); }
    bool send(const std::string& phone, const std::string& code)
    {
        AlibabaCloud::CommonRequest request(AlibabaCloud::CommonRequest::RequestPattern::RpcPattern);
        request.setHttpMethod(AlibabaCloud::HttpRequest::Method::Post);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setQueryParameter("Action", "SendSms");
        request.setQueryParameter("SignName", "outlier");               // 根据实际产品信息填写
        request.setQueryParameter("TemplateCode", "SMS_1111222233");    // 根据实际产品信息填写
        request.setQueryParameter("PhoneNumbers", phone);
        std::string paramCode = fmt::format(R"("code":"{}")", code);
        request.setQueryParameter("TemplateParam", paramCode);
        auto response = client_->commonResponse(request);
        if (!response.isSuccess()) {
            LOG_ERROR("短信验证码请求失败：{}", response.error().errorMessage());
            return false;
        }
        return true;
    }
private:
    std::unique_ptr<AlibabaCloud::CommonClient> client_;
};

using DMSClientPtr = std::shared_ptr<DMSClient>;

}}